﻿Imports System.Net.Mail

Partial Class Kindle
    Inherits Page

    Public ReadOnly Property Format As String
        Get
            Return CWeb.RequestStr("format")
        End Get
    End Property



    Public Sub Page_Init() Handles Me.Init
        Dim ss As New List(Of String)
        For Each i As CProduct In CProduct.Cache.Active.HavingTranscripts
            GetBits(i.ProductTranscription, ss)
        Next

        For Each i As String In ss
            Response.Write(i & "<br>" & vbCrLf)
        Next
        Response.End()



        If Not String.IsNullOrEmpty(Format) Then
            Select Case Format
                Case "html"
                    Response.ContentType = "text/html"
                    Response.WriteFile(CSitemap.HTML_PATH)
                Case "epub"
                    Response.AddHeader("content-disposition", "attachment;filename=latest.epub")
                    Response.ContentType = "binary/epub"
                    Response.WriteFile(CSitemap.EPUB_PATH)
                Case "mobi"
                    Response.AddHeader("content-disposition", "attachment;filename=latest.mobi")
                    Response.ContentType = "binary/mobi"
                    Response.WriteFile(CSitemap.MOBI_PATH)
            End Select
            Response.End()
        End If

        cbl.DataSource = CProduct.Cache.HavingTranscripts.SortByCreatedDescName
        cbl.DataBind()
        CDropdown.SelectAll(cbl)
        'tblSent.Visible = False

        lnkMobi.Text = String.Concat(lnkMobi.Text, " (", CUtilities.FileSize(CSitemap.MOBI_PATH), ")")
        lnkEpub.Text = String.Concat(lnkEpub.Text, " (", CUtilities.FileSize(CSitemap.EPUB_PATH), ")")
        lnkHtml.Text = String.Concat(lnkHtml.Text, " (", CUtilities.FileSize(CSitemap.HTML_PATH), ")")
    End Sub

    Private Sub GetBits(s As String, ss As List(Of String))
        Dim i As Integer = 0
        While i <> -1
            i = GetBits(s, ss, i)
        End While
    End Sub
    Private Function GetBits(s As String, ss As List(Of String), startAt As Integer) As Integer
        Dim i As Integer = s.IndexOf("[", startAt)
        If -1 = i Then Return i

        Dim j As Integer = s.IndexOf("]", i)
        Dim between As String = s.Substring(i + 1, j - 1 - i)
        If Not ss.Contains(between) Then ss.Add(between)

        Return s.IndexOf("[", j)
    End Function


    Protected Sub Kindle_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        pnl.Visible = rbl.SelectedIndex > 0
        tblSelect.Visible = rbl2.SelectedIndex > 0
        btnSend.Text = IIf(pnl.Visible, "Send to Kindle Device", "Send Email")
        lnkSupport.NavigateUrl = CSitemap.External_Donations
        lnkDeafSermons.NavigateUrl = CSitemap.Sermons & "?trans=1"
        lnkBack.NavigateUrl = CSitemap.Sermons

        If pnl.Visible Then
            If txt.Text.Length = 0 Then txt.Text = "@kindle.com"
        Else
            txt.Text = txt.Text.Replace("@kindle.com", String.Empty)
        End If
        'If rbl.SelectedIndex > 0 AndAlso txt.Text.Contains("@") Then txt.Text = txt.Text.Substring(0, txt.Text.IndexOf("@"))


    End Sub

    Protected Sub valNewOnes_ServerValidate(sender As Object, e As ServerValidateEventArgs) Handles cv.ServerValidate
        If rbl2.SelectedIndex > 0 Then
            e.IsValid = CDropdown.SelectedInts(cbl).Count > 0
            If Not e.IsValid Then cv.ErrorMessage = "No Products Selected"
            Exit Sub
        End If

        'Get the recipient to search on
        Dim recipient As String = txt.Text.ToLower.Trim
        Dim isKindle As Boolean = rbl.SelectedIndex > 0
        If isKindle Then
            If recipient.Contains("@") Then recipient = recipient.Substring(0, recipient.IndexOf("@"))
            recipient &= "kindle.com"
        End If

        'All transcripts, less the ones sent
        Dim productIds As List(Of Integer) = CProduct.Cache.HavingTranscripts.Ids
        For Each i As CSent In New CSent().SelectByTo(recipient)
            For Each j As Integer In CUtilities.StringToListInt(i.SentProductIds)
                If productIds.Contains(j) Then productIds.Remove(j)
            Next
        Next
        If productIds.Count = 0 Then e.IsValid = False
    End Sub

    Protected Sub chkAll_CheckedChanged(sender As Object, e As System.EventArgs) Handles chkAll.CheckedChanged
        If Not IsNothing(Page.AutoPostBackControl) AndAlso Page.AutoPostBackControl.ID = btnSend.ID Then Exit Sub
        If Not chkAll.Checked Then
            For Each i As ListItem In cbl.Items
                i.Selected = False
            Next
        Else
            CDropdown.SelectAll(cbl)
        End If
    End Sub

    Protected Sub btnSend_Click(sender As Object, e As System.EventArgs) Handles btnSend.Click
        If Not Page.IsValid Then Exit Sub

        Dim recipient As String = txt.Text.ToLower.Trim
        If recipient.Length = 0 Then Exit Sub

        Dim isKindle As Boolean = rbl.SelectedIndex > 0
        If isKindle Then
            If recipient.Contains("@") Then recipient = recipient.Substring(0, recipient.IndexOf("@"))
            recipient &= "@kindle.com"
        End If

        Dim productIds As List(Of Integer) = CDropdown.SelectedInts(cbl)
        If rbl2.SelectedIndex = 0 Then
            'All transcripts, less the ones sent
            productIds = CProduct.Cache.HavingTranscripts.Ids
            For Each i As CSent In New CSent().SelectByTo(recipient)
                For Each j As Integer In CUtilities.StringToListInt(i.SentProductIds)
                    If productIds.Contains(j) Then productIds.Remove(j)
                Next
            Next
        End If


        ''Display (debug only)
        'Dim html As String = CKindle.Build(productIds)
        'Response.Write(html)
        'Response.End()

        If isKindle Then
            SendAttachment(recipient, productIds)
        Else
            SendHtml(recipient, productIds)
        End If

        'Record the event
        With New CSent
            .SentProductIds = CUtilities.ListToString(productIds)
            .SentTo = recipient
            .SentIsKindle = isKindle
            .Save()
        End With

        rbl.SelectedIndex = 0
        rbl2.SelectedIndex = 0
        txt.Text = ""
        lblSent.Text = "An email was sent to: " & recipient
        If isKindle Then lblSent.Text = lblSent.Text.Replace("email", "ebook")
        tblSent.Visible = True
    End Sub

    Private Sub SendHtml(recipient As String, productIds As List(Of Integer))
        Dim k As New CKindle(Format)
        Dim html As String = k.Display(productIds)
        Dim title As String = CKindle.TitleFor(productIds)

        'Send the mail
        Dim msg As New MailMessage
        Try
            With msg
                .IsBodyHtml = True
                .To.Add(New MailAddress(recipient))
                .Subject = "Mike Connell Sermons: " & title
                .Body = html

                '*Sender is downloads.mikeconnellminstries.com (not gmail)
                .ReplyToList.Add(New MailAddress("mikeconnellministries@gmail.com", "Mike Connell Ministries"))
            End With

            With New SmtpClient
                .Send(msg)
            End With
            'CConfig.Gmail.Send(msg)
        Catch ex As Exception
            CAudit_Error.Log(ex, recipient, recipient)
        End Try
    End Sub

    Private Sub SendAttachment(recipient As String, productIds As List(Of Integer))
        'Get the mobi file
        Dim mobiPath As String = Nothing
        If productIds.Count = CProduct.Cache.Count - CProduct.Cache.GetByScribeId(0).Count Then
            'Use the custom-made one (with navigation)
            mobiPath = CSitemap.MOBI_PATH
        Else
            'Generate the mobi file, or use the stored copy
            Dim tempDir As String = Server.MapPath(String.Concat("~/app_data/", CUtilities.ListToString(productIds).GetHashCode, "/"))
            Dim name As String = CKindle.TitleFor(productIds).Replace("'", "").Replace(" ", "").Replace("-", "_")
            mobiPath = String.Concat(tempDir, name, ".mobi")
            If Not IO.File.Exists(mobiPath) Then
                If Not IO.Directory.Exists(tempDir) Then IO.Directory.CreateDirectory(tempDir)
                Dim k As New CKindle(Format)
                Dim html As String = k.Display(productIds)
                Dim htmPath As String = mobiPath.Substring(0, mobiPath.Length - 4) & "htm"
                If IO.File.Exists(htmPath) Then
                    System.Threading.Thread.Sleep(10000)
                Else
                    IO.File.WriteAllText(htmPath, html)
                    Dim exePath As String = Server.MapPath("~/app_data/kindlegen.exe")
                    System.Diagnostics.Process.Start(exePath, htmPath).WaitForExit()
                End If
            End If
        End If

        'Send the mail
        Dim msg As New MailMessage
        Try
            With msg
                .To.Add(New MailAddress(recipient))
                .Subject = "Mike Connell Sermons"

                Dim a As New Attachment(mobiPath)
                .Attachments.Add(a)
            End With

            With New SmtpClient
                .Send(msg)
            End With
            msg.Dispose()
            'CConfig.Gmail.Send(msg)
        Catch ex As Exception
            CAudit_Error.Log(ex, recipient, recipient)
        End Try
    End Sub

End Class
